#include "../include/head.h"
#define BUF_SIZE 4096


typedef struct{
    OP truck_op; //命令状态码
    int truck_len; //火车头，表示数据长度
    char truck_data[BUF_SIZE]; //火车厢，表示数据
}Truck_t;

int login(int sockfd){

    char username[4096] = {0};
    printf("请输入用户名：\n");
    scanf("%s",username);

    Truck_t truck;
    truck.truck_op = OP_LOGIN;
    truck.truck_len = strlen(username);
    memcpy(truck.truck_data ,username,truck.truck_len);

    send(sockfd,&truck.truck_op,sizeof(truck.truck_op),0);
    send(sockfd,&truck.truck_len,sizeof(truck.truck_len),0);
    send(sockfd,truck.truck_data,truck.truck_len,0);

    bzero(&truck,sizeof(Truck_t));
    recv(sockfd,&truck.truck_op,sizeof(truck.truck_op),0);
    recv(sockfd,&truck.truck_len,sizeof(truck.truck_len),0);
    recv(sockfd,truck.truck_data,truck.truck_len,0);

    if(truck.truck_op == OP_SUC){
        char password[4096] = {0};
        printf("请输入您的密码：\n");
        scanf("%s",password);
        
        printf("%s\n",truck.truck_data);        
        char salt[4096] = {0};
        memcpy(salt,truck.truck_data,truck.truck_len);
        
        char ciphertext[256] = {0};
        char *str = crypt(password,salt);
        strcpy(ciphertext,str);
        
        bzero(&truck,sizeof(Truck_t));
        truck.truck_len = strlen(ciphertext);
        memcpy(truck.truck_data,ciphertext,truck.truck_len);

        send(sockfd,&truck.truck_len,sizeof(truck.truck_len),0);
        send(sockfd,truck.truck_data,truck.truck_len,0);
    }else{
        printf("%s\n",truck.truck_data);
        return -1;
    }
    bzero(&truck,sizeof(Truck_t));
    recv(sockfd,&truck.truck_op,sizeof(truck.truck_op),0);
    recv(sockfd,&truck.truck_len,sizeof(truck.truck_len),0);
    recv(sockfd,truck.truck_data,truck.truck_len,0);

    if(truck.truck_op == OP_SUC){
        printf("%s\n",truck.truck_data);
    }else{
        printf("%s\n",truck.truck_data);
    }
    return 0;
}

